﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CellularAutomation.Core;
using CellularAutomation.IView;

namespace CellularAutomation.Presenter
{
	public class Presenter
	{
		#region Private Fields

		/// <summary>
		/// Модель MVP
		/// </summary>
		private Grid _grid;

		/// <summary>
		/// Интерфейс вьюхи
		/// </summary>
		private ICellAutoView _view;

		#endregion


		#region Constructors

		public Presenter(ICellAutoView view)
		{
			this._view = view;
			_view.CreateGrid += this.OnViewCreateGrid;
		}

		#endregion


		#region Private Methods

		/// <summary>
		/// Обработка события запроса следующего шага КА
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void OnNextOneStep(object sender, EventArgs e)
		{
			_grid.NextStep();
			this.RefreshView();
		}

		/// <summary>
		/// Обработка события изменения состояния клетки
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void OnCellStateChanged(object sender, CellStateChangedEventArgs e)
		{
			_grid.ChangeCellState(e.Position.X, e.Position.Y);
			this.RefreshView();
		}

		/// <summary>
		/// Обработка события создания решетки КА
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void OnViewCreateGrid(object sender, CreateGridEventArgs e)
		{
			var isInitializedBefore = _grid != null;
			
			_grid = new Grid(e.SizeX, e.SizeY);
			if (!isInitializedBefore)
			{
				_view.CellStateChanged += this.OnCellStateChanged;
				_view.NextOneStep += this.OnNextOneStep;
			}
			this.RefreshView();
		}

		/// <summary>
		/// Метод обновления вьюхи
		/// </summary>
		private void RefreshView()
		{
			//var dt = _grid.GetStateDataTable();
			//_view.SetStateTable(dt);
			var cellsList = _grid.GetAliveCellsList();
			_view.SetAliveCellCoordList(cellsList);
		}

		#endregion
	}
}
